<template>
  <div class="usrs-container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入搜索内容" 
          @clear="getUserList"
          v-model="usersInfo.query"
          clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
           <el-button type="primary" @click="addUserVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表表格区域 -->
      <el-table :data="userList" border>
        <el-table-column type="index" label="id"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="statuChange(scope.row)">
            </el-switch>
          </template>
          
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini"
            @click="showEditUser(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="角色管理" placement="top" :enterable="false">
              <!-- 角色管理按钮 -->
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页导航区域 -->、
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersInfo.pagenum"
        :page-sizes="[2, 5, 10]"
        :page-size="usersInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum">
      </el-pagination>
    </el-card>
    <!-- 添加用户 弹出框 -->
    <el-dialog title="添加用户" :visible.sync="addUserVisible" width="50%"
    @close="addUserClose">
      <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息 弹出框 -->
    <el-dialog
      title="修改用户信息" :visible.sync="editUserVisible" width="50%">
      <el-form :model="editUserForm" :rules="editUserRules" ref="editUserRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 弹出框 -->
    <el-dialog title="角色分配" :visible.sync="setRolesVisible" width="50%"
    @close="closeRights">
      <div>
        <p>当前用户: {{rolesInfo.username}}</p>
        <p>当前角色: {{rolesInfo.role_name}}</p>
        <p>分配新角色: 
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data(){
    // 自定义邮箱验证规则
      var checkEmail = (rule,value, cb) =>{
        const regEmail = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
        if(regEmail.test(value)) return cb();
        cb(new Error("请输入合法的邮箱！"));
      }
      // 自定义手机号验证规则
      var checkMobile = (rule,value, cb) =>{
        const regMobile =  /0?(13|14|15|18|17)[0-9]{9}/
        if(regMobile.test(value)) return cb();
        cb(new Error("请输入合法的手机号！"));
      }
    return{
      // 用户列表信息
      usersInfo:{
        query:'',
        // 当前页码值
        pagenum: 1,
        // 每页数量
        pagesize: 2
      },
      userList:[],
      totalNum:0,
      // 控制添加用户弹框的出现
      addUserVisible:false,
      // 控制修改用户信息弹框的出现
      editUserVisible:false,
      // 控制分配角色弹框的出现
      setRolesVisible:false,
      // 添加用户信息
      addUserForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      // 修改用户信息
      editUserForm:{
        id:'',
        email:'',
        mobile:''
      },
      // 修改用户信息规则
      editUserRules:{
        email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 10, max: 20, message: '长度在 10 到 20 个字符', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur', message: '请输入合法的邮箱！'}
          ],
          mobile: [
            { required: true, message: '请输入电话', trigger: 'blur' },
            { min: 6, max: 11, message: '长度在 6 到 11 个字符', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur', message: '请输入合法的手机号！'}
          ]
      },
      // 添加用户信息规则
      addUserRules:{
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 10, max: 20, message: '长度在 10 到 20 个字符', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur', message: '请输入合法的邮箱！'}
          ],
          mobile: [
            { required: true, message: '请输入电话', trigger: 'blur' },
            { min: 6, max: 11, message: '长度在 6 到 11 个字符', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur', message: '请输入合法的手机号！'}
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur' }
          ],
      },
      // 分配角色信息数据
      rolesInfo:{},
      // 所有角色列表
      roleList:[],
      // 选中角色的id
      selectRoleId:''
    }
  },
  created(){
    this.getUserList();
  },
  methods:{
    // 定义获取用户列表方法
    async getUserList(){
     const { data :res} = await this.$http.get('users', { params: this.usersInfo});
    //  console.log(res);
     if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
     this.userList = res.data.users;
     this.totalNum = res.data.total;
    //  console.log("================");
    //  console.log(this.userList);
    },
    // 监听每页显示的数量改变
    handleSizeChange(nweSize){
      // console.log(nweSize);
      // 每页数量改变时赋值给pagenum
      this.usersInfo.pagesize = nweSize;
      this.getUserList();
    },
    // 监听页码值的改变
    handleCurrentChange(newPage){
      // console.log(newPage);
      this.usersInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听用户状态改变
    async statuChange(newValue){
      // 调用put请求，修改状态
      const { data: res } = await this.$http.put(`users/${ newValue.id}/state/${ newValue.mg_state}`);
      if(res.meta.status !== 200 ){
        this.$message.error(res.meta.msg);
        newValue.status = !newValue.status;
      } else{
         this.$message.success("修改状态成功！");
      }
       
    },
    // 监听 添加用户对话框 关闭事件
    addUserClose(){
      this.$refs.addUserRef.resetFields();
    },
    // 添加用户方法
    addUser(){
      // 表单提交的预校验
      this.$refs.addUserRef.validate(async valid => {
        if(!valid) return this.$message.error("表单提交失败");
        // 发起网络请求，添加新用户
        const { data: res } = await this.$http.post("users", this.addUserForm );
        if(res.meta.status !== 201){
          this.$message.error(res.meta.msg);
        }else{
          this.$message.success("添加用户成功！");
          this.addUserVisible = false;
          this.getUserList();
        }     
      });
    },
    // 展示修改用户信息对话框
    async showEditUser(id){
     const { data: res } = await this.$http.get("users/" + id, );
    //  console.log(res);
    if(res.meta.status !== 200){
      this.$message.error(res.meta.msg);
    }
      this.editUserForm = res.data;
      this.editUserVisible = true;
    },
    // 监听 修改用户对话框 关闭事件
    addUserClose(){
      this.$refs.editUserRef.resetFields();
    },
    // 修改用户信息方法
    editUser(){
      // 表单提交的预校验
      this.$refs.editUserRef.validate(async valid => {
        if(!valid) return this.$message.error("修改用户信息失败！");
        // 发起网络请求，修改用户信息
        const { data: res } = await this.$http.put("users/" + this.editUserForm.id,
        { mobile: this.editUserForm.mobile,
          email: this.editUserForm.email  } );
        if(res.meta.status !== 200){
          this.$message.error(res.meta.msg);
        }else{
          this.$message.success("修改用户信息成功！");
          this.editUserVisible = false;
          this.getUserList();
        }     
      });
    },
    // 删除用户方法
    async removeUser(id){
      // 提示用户是否确认删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).catch(err => err);
        // 如果用户确认删除,返回字符串confirm
        // 如果用户取消删除,返回字符串cancel
        // 判断用户是否真的删除
        if(confirmResult !== 'confirm'){
          return this.$message.info("已取消删除");
        }
        const {data: res} = await this.$http.delete("users/" + id);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("用户成功删除")
        this.getUserList();
    },
    // 展示 角色分配 对话框
    async showSetRole(userInfo){
      this.rolesInfo = userInfo;
      this.setRolesVisible = true;
      // console.log(this.rolesInfo);
      // 请求角色列表
      const { data: res } = await this.$http.get("roles");
      if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.roleList = res.data;
        // console.log(this.roleList);

    },
    // 保存分配角色结果方法
    async saveRole(){
      if(!this.selectRoleId){
        return this.$message.error('请选择要分配的角色!');
      }
      const { data: res } = await this.$http.put(`users/${ this.rolesInfo.id }/role`,
      {rid: this.selectRoleId });
      if(res.meta.status !== 200){
        return this.$message.error("修改角色失败!");
      }
      this.$message.success("修改角色成功!");
      this.getUserList();
      this.setRolesVisible = false;
    },
    // 监听关闭分配角色对话框事件
    closeRights(){
      this.selectRoleId = ''
      this.rolesInfo = '';
    }
  }
}
</script>

<style lang="less" scoped>

</style>